// ==UserScript==
// @name         nMusic: Spotifier
// @version      0.1
// @description  Allows nMusic to login as you on Spotify.
// @author       <null>
// @match        https://open.spotify.com/*/*
// @grant        none
// @run-at document-idle
// NOTE: This userscript is unused for now, you don't need to install it.
// ==/UserScript==

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function base64Encode(str) {
    try {
 		return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
            return String.fromCharCode(parseInt(p1, 16))
    	}));
 	 }catch (ex) {
 	 	return btoa(str);
	 }
}

(function() {
    'use strict';
    function inject(element) {
        console.log("[nMusic] Injecting into Spotify...");
        // inject button
        var y = document.getElementsByClassName("link-subtle navBar-link ellipsis-one-line")[2].parentNode.parentNode;
        console.log(y);
        var d = document.createElement("div");
        d.className = "navBar-item navBar-item--with-icon-left";
        y.appendChild(d);
        var x = document.createElement("p");
        x.innerHTML = "Login into nMusic.";
        x.style.paddingTop = "5px";
        x.style.textAlign = "center";
        d.appendChild(x);
        x.onclick = function() {
            const access_token = getCookie("wp_access_token");
            const sp_t = getCookie("sp_t");
            const wp_expiration = getCookie("wp_expiration");
            const sp_key = getCookie("sp_key");
            var obj = {
                token: access_token,
                sp_t: sp_t,
                expriation: wp_expiration,
                key: sp_key
            };
            const result = base64Encode(JSON.stringify(obj));
            navigator.clipboard.writeText(result).then(function() {
                alert("Copied to clipboard. Copy it in the nMusic login window.");
            }).catch(function(e) {
		console.error(e);
                alert("uhmmm.");
            });
        }
    }

    var observer = new MutationObserver(function (mutations, me) {
        var element = document.getElementsByClassName("link-subtle navBar-link ellipsis-one-line")[2];
        if (element) {
            inject(element);
            me.disconnect();
            return;
        }
    });

    observer.observe(document, {
        childList: true,
        subtree: true
    });
})();